import { getSearchApi, getSearchResultApi } from '@/api/search';
import store, { AppDispatch } from '..';

export const getSearchAction = (keyword: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchApi(keyword);
    dispatch({ type: 'search/setSearch', payload: res.data.options });
  };
};
// 清空搜索
export const clearSearchAction = () => {
  return (dispatch: AppDispatch) => {
    dispatch({ type: 'search/clearSearch', payload: [] });
  };
};
//保存搜索历史记录
export const setHistoryListAction = (list: string[]) => ({
  type: 'search/setHistory',
  payload: list,
});
//清除搜索历史记录
export const clearHistoryListAction = () => ({
  type: 'search/clearHistory',
  payload: [],
});

//获取搜索结果 加载更多搜索结果
export const getSearchResultAction = (q: string, page?: number) => {
  return async (dispatch: AppDispatch) => {
    const res = await getSearchResultApi(q, page);
    dispatch({ type: 'search/setSearchResult', payload: res.data });
  };
};
//清除搜索结果
export const clearSearchResultAction = () => ({
  type: 'search/clearSearchResult',
  payload: {},
});

// //加载更多搜索结果
// export const getMoreSearchResultAction = (q: string, page: number) => {
//   return async (dispatch: AppDispatch, getState: typeof store.getState) => {
//     //获取旧数据
//     const { resultData } = getState().search;
//     //获取新数据
//     const res = await getSearchResultApi(q, page);
//     //合并数据 取出旧数据和新数据的results进行合并
//     const newResultData = {
//       ...resultData,
//       ...res.data,
//       results: [...resultData.results, ...res.data.results],
//     };
//     //保存数据
//     dispatch({ type: 'search/setSearchResult', payload: newResultData });
//   };
// };
